package com.swt.gap.util;

import org.springframework.util.Base64Utils;

import java.io.*;

public class Base64ToImgUtil {

    public static String imgToBase64(String filePath){
        InputStream in = null;
        byte[] data = null;
        String encode = null;

        try {
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            encode = Base64Utils.encodeToString(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return encode;
    }

    public static boolean base64ToImg(String base64Str, String imgPath){
        if (base64Str == null || base64Str.isEmpty()){
            return false;
        }

        OutputStream fileOutputStream = null;
            try {
                byte[] decode = Base64Utils.decodeFromString(base64Str);
                fileOutputStream = new FileOutputStream(imgPath);
                for (int i = 0; i < decode.length; ++i) {
                    if (decode[i] < 0) {
                        decode[i] += 256;
                    }
                }
                fileOutputStream.write(decode);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }finally {

                try {
                    if(fileOutputStream != null){
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }

                }catch (IOException e) {
                    return false;
                }

                return true;
            }
    }



}
